import { useNavigate } from 'react-router-dom';
import { useContext, useState } from 'react';
import { BaseContext } from '../../context';
import './index.less';

const Add = () => {
  const navigate = useNavigate();
  const { tasks, setTasks } = useContext(BaseContext);

  const [formData, setFormData] = useState({
    title: '',
    desc: '',
    priority: '',
    state: ''
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Form submitted:', formData);
    setTasks([...tasks, { id: tasks.length + 1, ...formData, priority: Number(formData.priority) }]);
    alert('新增成功');
    navigate('/');
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <div>
          <label>任务名称:</label>
          <input
            name="title"
            value={formData.title}
            onChange={handleChange}
            required
          />
        </div>
        <div>
          <label>任务描述:</label>
          <textarea
            name="desc"
            value={formData.desc}
            onChange={handleChange}
            required
          />
        </div>
        <div>
          <label>优先级:</label>
          <select
            name="priority"
            value={formData.priority}
            onChange={handleChange}
            required
          >
            <option value="">请选择优先级</option>
            <option value={1}>1</option>
            <option value={2}>2</option>
            <option value={3}>3</option>
          </select>
        </div>
        <div>
          <label>任务状态:</label>
          <select
            name="state"
            value={formData.state}
            onChange={handleChange}
            required
          >
            <option value="">请选择任务状态</option>
            <option value="未开始">未开始</option>
            <option value="进行中">进行中</option>
            <option value="已完成">已完成</option>
          </select>
        </div>
        <div className="btn-col">
          <button className="back-button" onClick={() => navigate('/')}>返回</button>
          <button type="submit" className="submit-button">提交</button>
        </div>
      </form>
    </div>
  );
};

export default Add;